<?php

namespace App\Libraries\Common;

use Illuminate\Support\Facades\Redis;

trait RedisHelper
{
    protected $redis_name = null;

    public function getRedisData()
    {
        $data = json_decode(Redis::get($this->redis_name));
        if (null == $data) {
            $data = $this->model->all();
            Redis::set($this->redis_name, $data);
        }

        return $data;
    }

    public function resetRedisData()
    {
        if (null != $this->redis_name) {
            Redis::del($this->redis_name);
        }
    }

    public function getRedisDataByName($name, $getFunc)
    {
        $data = Redis::get($name);
        if (null === $data) {
            $data = call_user_func($getFunc);
            $data = json_encode(call_user_func($getFunc));

            Redis::set($name, $data);
        }
        $data = json_decode($data);

        return $data;
    }

    public function getRedisDataByNameWithData($name, $initData)
    {
        $data = Redis::get($name);
        if (null === $data) {
            $data = json_encode($initData);
            Redis::set($name, $data);
        }
        $data = json_decode($data);

        return $data;
    }

    public function resetRedisDataByName($name)
    {
        Redis::del($name);
    }
}
